package com.tarena.luban.demo.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.sql.SQLOutput;
import java.util.List;
import java.util.function.Supplier;

/*
实现接口
 */
@Component
public class MyFilter01 implements GlobalFilter, Ordered {
    /**
     * @param exchange 交换机spring webflux框架 包装了请求和响应的对象
     * @param chain 过滤链的对象,处理完过滤逻辑,到底要如何整合回过滤链
     * @return Mono 纯粹的spring webflux(函数式编程 lamda) 在这只关注如何用api生成对应Mono
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("请求进入到过滤器01");
        //案例1的逻辑 ,从request获取path uri
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径
        URI uri = request.getURI();
        System.out.println("URI:"+uri.toString());
        RequestPath path = request.getPath();
        System.out.println("path:"+path.toString());
        ServerHttpResponse response = exchange.getResponse();
        //案例2的逻辑 ?name=wang&jobs%5B0%5D=police&jobs%5B1%5D=docter
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        // name List<String> 元素是一个 值是wang
        // jobs List<String> 元素有2个 0 police 1 docter
        boolean exists = queryParams.containsKey("toten");
        if (exists){
            //存在则合法
            Mono<Void> filter = chain.filter(exchange);
            return filter;
        }else {
            //为了防止乱码 contentType "application/json;charset=utf-8"
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            //TODO 一般返回一个Result对象
            //response响应数据 输出回客户端
            return response.writeWith(Mono.fromSupplier(new Supplier<DataBuffer>() {
                @Override
                public DataBuffer get() {
                    //响应体的字符串
                    String json="你没有携带token";
                    return response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
                }
            }));
        }
    }

    @Override
    public int getOrder() {
        //二进制长什么样 1 31个0
        //32个1 -1
        //最大正整数2进制 31位个1
        return Integer.MIN_VALUE;
    }
}
